import { db } from "../db/index.ts";
import { accessTokens } from "../db/schema.ts";
import { eq, and } from "drizzle-orm";
import { timestamp } from "ph-utils/date";
import { logger } from "../utils/logger.ts";
import type { H3Event } from "h3";
import { HTTPError } from "h3";

function accessTokenError(error: string, description: string) {
  return HTTPError.status(401, "Unauthorized", {
    message: "Invalid token",
    body: {
      error: error,
      error_description: description,
    },
    headers: {
      "WWW-Authenticate": `Bearer error="${error}", error_description="${description}"`,
    },
  });
}
export async function readAccessToken(e: H3Event) {
  const tokenHeader = e.req.headers.get("Authorization");
  const appid = e.context.appid as string;
  if (!tokenHeader || !tokenHeader.startsWith("Bearer ")) {
    throw accessTokenError(
      "invalid_request",
      "Missing or invalid Authorization header",
    );
  }
  const token = tokenHeader.substring(7);
  const result = await (db().query as any).accessTokens.findFirst({
    where: and(
      eq(accessTokens.accessToken, token),
      eq(accessTokens.appid, appid),
    ),
  });
  if (result) {
    const expires = timestamp(result.expiresAt);
    const now = timestamp();
    if (expires > now) {
      return {
        accessToken: result.accessToken as string,
        userId: result.userId as number,
      };
    } else {
      logger.info("Access token expired");
      throw accessTokenError("expired_token", "Access token expired");
    }
  } else {
    logger.info("Invalid access token");
    throw accessTokenError("invalid_token", "Invalid access token");
  }
}
